<template>
  <div>
    <div><warning-bar title="注：新增角色后请分配权限" /></div>
    <div>
      <el-card>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-button type="primary" plain @click="addAuthority"
              >新增角色</el-button
            >
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-divider />
        <el-row :gutter="20" class="mt-5">
          <el-col :span="24">
            <el-table
              v-loading="loading"
              :data="tableData"
              style="width: 100%"
              ref="TableRef"
              empty-text="暂无数据"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column
                align="center"
                prop="authorityId"
                label="编号"
                width="320"
              />
              <el-table-column
                align="center"
                prop="authorityName"
                label="名称"
                width="350"
              />
              <el-table-column align="center" label="创建时间" width="200">
                <template #default="scope">{{
                  formatDate(scope.row.created_at)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="更新时间" width="200">
                <template #default="scope">{{
                  formatDate(scope.row.updated_at)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template #default="scope">
                  <el-button
                    link
                    icon="setting"
                    type="primary"
                    size="small"
                    @click="opdendrawer(scope.row)"
                    >分配权限</el-button
                  >
                  <el-button
                    link
                    icon="edit"
                    type="primary"
                    size="small"
                    @click="editAuthority(scope.row)"
                    >修改</el-button
                  >
                  <el-button
                    link
                    icon="delete"
                    type="primary"
                    size="small"
                    @click="openDeleteAuthority(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table></el-col
          >
        </el-row>
        <div class="mt-2">
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>
    </div>
    <div>
      <el-drawer
        v-if="drawer"
        v-model="drawer"
        custom-class="auth-drawer"
        :with-header="false"
        size="40%"
        title="角色配置"
      >
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="菜单权限" name="menus">
            <Menus ref="menus" :row="activeRow" />
          </el-tab-pane>
          <el-tab-pane label="接口权限" name="apis">
            <Apis ref="apis" :row="activeRow" />
          </el-tab-pane>
        </el-tabs>
      </el-drawer>

      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="30%"
        draggable
      >
        <el-form
          ref="authorityForm"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="角色ID" prop="authorityId">
            <el-input
              v-model.number="form.authorityId"
              :disabled="dialogType == 'edit'"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="角色名称" prop="authorityName">
            <el-input v-model="form.authorityName" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="doAddOrUpdate"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import WarningBar from "~/components/messageBar/warningBar.vue";
import { formatDate } from "~/utils/format";
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import Apis from "./components/apis.vue";
import Menus from "./components/Menus.vue";
import { message } from "~/utils/utils.js";
import {
  getAuthorityList,
  deleteAuthority,
  createAuthority,
  updateAuthority,
} from "~/api/authority";

const loading = ref(true);
const page = ref(1);
const total = ref(0);
const searchInfo = ref("");
const pageSize = ref(10);
const tableData = ref([]);
const TableRef = ref(null);
const multipleSelection = ref([]);

// 正整数检验器
const mustUint = (rule, value, callback) => {
  if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
    return callback(new Error("请输入正整数"));
  }
  return callback();
};
//dialog相关
// 表单初始化函数
const initForm = () => {
  if (authorityForm.value) {
    authorityForm.value.resetFields();
  }
  form.value = {
    authorityId: 0,
    authorityName: "",
  };
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getAuthList();
};

const handleCurrentChange = (val) => {
  page.value = val;
  getAuthList();
};

// 新增修改dialog
const form = ref({
  authorityId: 0,
  authorityName: "",
});
// 表单校验
const rules = ref({
  authorityId: [
    { required: true, message: "请输入角色ID", trigger: "blur" },
    { validator: mustUint, trigger: "blur", message: "必须为正整数" },
  ],
  authorityName: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
  ],
});
// 表单ref
const authorityForm = ref(null);
const dialogVisible = ref(false);
const dialogType = ref("add");
const dialogTitle = ref("新增角色");

const drawer = ref(false);
const activeRow = ref({});
const opdendrawer = (row) => {
  drawer.value = true;
  activeRow.value = row;
};

// 增加角色
const addAuthority = () => {
  initForm();
  dialogVisible.value = true;
  dialogTitle.value = "新增角色";
  dialogType.value = "add";
};
// 编辑角色
const editAuthority = (row) => {
  dialogVisible.value = true;
  dialogTitle.value = "编辑角色";
  dialogType.value = "edit";
  for (const key in form.value) {
    form.value[key] = row[key];
  }
};
// 增加或删除向后端发起请求
const doAddOrUpdate = () => {
  authorityForm.value.validate(async (valid) => {
    if (valid) {
      switch (dialogType.value) {
        case "add":
          const addRes = await createAuthority(form.value);
          if (addRes) {
            dialogVisible.value = false;
            message(addRes);
            getAuthList();
          }
          break;
        case "edit":
          const editRes = await updateAuthority(form.value);
          if (editRes) {
            dialogVisible.value = false;
            message(editRes);
            getAuthList();
          }
          break;
      }
    }
  });
};

// 删除角色
const openDeleteAuthority = (row) => {
  ElMessageBox.confirm(
    `此操作将会删除角色,请确认[${row.authorityName}]未绑定任何用户`,
    "删除角色",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "Warning",
    }
  ).then(async () => {
    console.log(row);
    const res = await deleteAuthority(row.authorityId);
    if (res) {
      message(res);
      getAuthList();
    }
  });
};

// tab相关
const activeTab = ref("menus");

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 获取角色列表
const getAuthList = async () => {
  const res = await getAuthorityList({
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value,
  });
  if (res) {
    total.value = res.total;
    page.value = res.page;
    pageSize.value = res.pageSize;
    tableData.value = res.list;
    loading.value = false;
  }
};
getAuthList();
</script>
